package com.yan.common.file.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.yan.common.file.mapper.FileMapper;
import com.yan.common.login.model.LoginUser;
import com.yan.common.user.mapper.SysUserMapper;
import com.yan.common.util.ConfUtil;
import com.yan.common.util.UUIDHexGenerator;
import com.yan.core.annotation.MapperInject;
import com.yan.core.controller.BaseController;
import com.yan.core.model.MsgModel;
import com.yan.core.model.PageModel;

/**
 * 文件列表管理
 * 
 * @author bigbug
 *
 */
@Controller
@RequestMapping("/common/file")
public class FileController extends BaseController {

	@MapperInject(FileMapper.class)
	private FileMapper mapper;

	@RequestMapping("/manage")
	public String manage() {
		return "common/file/manage";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public PageModel<HashMap<String, Object>> list(@RequestParam HashMap<String, Object> params) {
		params.put("token", this.getSession().getAttribute("token")+"");
		PageModel pageModel = new PageModel();
		String offset = (String) params.get("offset");
		String limit = (String) params.get("limit");
		Integer iter = Integer.parseInt(offset);
		Integer limitInt = Integer.parseInt(limit);
		String end = (iter + limitInt) + "";
		params.put("limit", end);
		LoginUser loginUser = this.getSessionUser();
		String userName =loginUser.getUserCode();
		String loginId =loginUser.getUserId();
		params.put("loginId", loginId);
		// 查询列表
		List<HashMap<String, Object>> listResult = mapper.queryFileList(params);
		// 统计查询
		Integer count = mapper.queryFileCount(params);
		//查询超级管理员分配的数据
		pageModel.setRows(listResult);
		pageModel.setTotal(count);
		return pageModel;
	}

	/**
	 * @throws IOException
	 * @throws IllegalStateException
	 * @方法描述: 文件上传 @作者： 易涛 @时间： 2018年5月21日上午11:59:43
	 * @参数 @param params
	 * @参数 @return @返回类型： MsgModel
	 */
	@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
	@ResponseBody
	public MsgModel uploadImage(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
		// 公司的Id
		if (!file.isEmpty()) {
			// 获取根路径
			String path = this.getClass().getResource("/properties/setting.properties").getPath();
			String uploadPath = ConfUtil.getInstance().getConfValue(path, "setting.upload");
			// 根据sessionid 设置上传路径，退出之后普通用户无法 看到上传过的文件
			String showPath = this.getSession().getId() + "/";
			// 上传文件路径
			String realPath = uploadPath + "/" + this.getSession().getId() + "/";
			File dirFile = new File(realPath);
			// 如果目录不存在，就创建目录
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			// 得到上传的文件名称
			String filename = file.getOriginalFilename();
			// 生成新的文件名称
			String newFileName = System.currentTimeMillis() + "." + filename.split("\\.")[1];
			// 将上传文件保存到一个目标文件当中
			file.transferTo(new File(realPath + File.separator + newFileName));
			return this.resultMsg("0", showPath + newFileName);
		} else {
			return this.resultMsg("-1", "上传失败！");
		}
	}

	/**
	 * @方法描述: 新增或者修改文件
	 * @参数 @param params
	 * @参数 @return @返回类型： MsgModel
	 */
	@RequestMapping(value = "/insertFile", method = RequestMethod.POST)
	@ResponseBody
	public MsgModel insertFile(@RequestParam HashMap<String, Object> params) {
		String fileId = params.get("id") + "";
		LoginUser loginUser = this.getSessionUser();
		params.put("createName", loginUser.getUserName());
		params.put("token", this.getSession().getAttribute("token")+"");
		int result = 0;
		if (this.isNull(fileId)) {// 如果文件新增
			params.put("createId", loginUser.getUserId());
			params.put("id", UUIDHexGenerator.generator());
			result = mapper.insertFile(params);
		} else {// 如果文件修改
			result = mapper.updateFile(params);
		}
		if (result > 0) {
			return this.resultMsg("0", "文件入库成功！", result);
		} else {
			return this.resultMsg("-1", "文件入库失败！");
		}
	}

	/**
	 * 将获取的数据导出到excel中
	 * 
	 * @param params
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/dowland", method = RequestMethod.GET)
	@ResponseBody
	public void dowland(@RequestParam HashMap<String, Object> params, HttpServletResponse response) throws Exception {
		try {
			String path = this.getClass().getResource("/properties/setting.properties").getPath();
			String uploadPath = ConfUtil.getInstance().getConfValue(path, "setting.upload");
			String filePath = (String) params.get("filePath");
			String realFilePath = uploadPath + "/" + filePath;
			// 拼凑路径
			String arg[] = filePath.split(",");
			InputStream is = new FileInputStream(realFilePath);
			response.setContentType("application/x-download");// 下面三行是关键代码，处理乱码问题
			response.setCharacterEncoding("utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String(arg[arg.length - 1].getBytes("gbk"), "iso8859-1"));
			OutputStream out = response.getOutputStream();
			int data;
			while (is.available() > 0) {
				data = is.read();
				out.write(data);
			}
			is.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/showImage")
	public @ResponseBody void showImage(String filePath) throws IOException {
		String ext = filePath.substring(filePath.indexOf(".") + 1);
		String mimeType = "";
		switch (ext) {
		case "png":
		case "PNG":
			mimeType = "image/png";
			break;
		case "jpg":
		case "jpeg":
		case "JPEG":
		case "JPG":
			mimeType = "image/jpeg";
			break;
		case "GIF":
		case "gif":
			mimeType = "image/gif";
			break;
		case "pdf":
		case "PDF":
			mimeType = " application/pdf";
			break;
		case "doc":
			mimeType = "application/msword";
			break;
		case "docx":
			mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
			break;
		case "xls":
			mimeType = "application/vnd.ms-excel";
			break;
		case "xlsx":
			mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
			break;
		case "txt":
		case "TXT":
			mimeType = "text/plain"; 
			break;
		case "rtf":
		case "RTF":
			mimeType = "application/rtf"; 
			break;
		default:
			mimeType = "application/json";
			break;
		}
		getResponse().setContentType("text/html; charset=UTF-8");
		getResponse().setContentType(mimeType);
		String path = this.getClass().getResource("/properties/setting.properties").getPath();
		String uploadPath = ConfUtil.getInstance().getConfValue(path, "setting.upload");
		String realFilePath = uploadPath + "/" + filePath;
		FileInputStream fis = new FileInputStream(realFilePath);
		OutputStream os = getResponse().getOutputStream();
		try {
			int count = 0;
			byte[] buffer = new byte[1024 * 1024];
			while ((count = fis.read(buffer)) != -1)
				os.write(buffer, 0, count);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
			if (fis != null)
				fis.close();
		}
	}
	
	//文件删除
	@RequestMapping(value = "/deleteFile", method = RequestMethod.POST)
	@ResponseBody
	public MsgModel deleteFile(@RequestParam HashMap<String, Object> params) {
		
		
		Integer row = mapper.deleteFile(params);
		String filePath =(String) params.get("filePath");
		if(! (filePath==null))
			FileController.delete(filePath);
		return this.resultMsg("0", "删除成功！", params);
	}
	
	//获取授权 账号集合queryRightUsers
	@RequestMapping(value = "/queryRightUsers", method = RequestMethod.POST)
	@ResponseBody
	public MsgModel queryRightUsers(@RequestParam HashMap<String, Object> params) {
		HashMap<String, Object> result = new HashMap ();
		List<HashMap> listRightUsers = mapper.queryRightUsers(params);
		
		List<HashMap> checkedUsers =mapper.queryCheckedUsers(params);
		result.put("listRightUsers", listRightUsers);
		result.put("checkedUsers", checkedUsers);
		return this.resultMsg("0", "成功！", result);
	}
	
	//重新授权
	
	@RequestMapping(value = "/updateRightUsers", method = RequestMethod.POST)
	@ResponseBody
	public MsgModel updateRightUsers(@RequestParam HashMap<String, Object> params) {
		
		//删除原有授权
		mapper.deleteRightUsers(params);
		//重新授权insertUserFile insertMemberFile
		String userCheck =(String) params.get("userCheck");
		String memberCheck =(String) params.get("memberCheck");
		if("true".equals(userCheck)){
			params.put("id", UUID.randomUUID().toString());
			mapper.insertUserFile(params);
			
		}
		if("true".equals(memberCheck)){
			params.put("userId", params.get("memberId"));
			params.put("id", UUID.randomUUID().toString());
			mapper.insertUserFile(params);
			
		}
		
		return this.resultMsg("0", "成功！");
	}
	
	
	
	

	public static boolean delete(String fileName) {
	        File file = new File(fileName);
	        if (!file.exists()) {
	            System.out.println("删除文件失败:" + fileName + "不存在！");
	            return false;
	        } else {
	           
	                return deleteFile(fileName);
	           
	        }
	    }
	 
	 /**
	     * 删除单个文件
	     *
	     * @param fileName
	     *            要删除的文件的文件名
	     * @return 单个文件删除成功返回true，否则返回false
	     */
	    public static boolean deleteFile(String fileName) {
	        File file = new File(fileName);
	        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
	        if (file.exists() && file.isFile()) {
	            if (file.delete()) {
	                System.out.println("删除单个文件" + fileName + "成功！");
	                return true;
	            } else {
	                System.out.println("删除单个文件" + fileName + "失败！");
	                return false;
	            }
	        } else {
	            System.out.println("删除单个文件失败：" + fileName + "不存在！");
	            return false;
	        }
	    }
	
}
